/**
 * 
 */
package org.dc.agent.util;

import org.apache.log4j.Logger;
import org.dc.agent.configoper.GetConfig;
import org.dc.agent.job.SnmpJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.snmp4j.Snmp;

import java.text.ParseException;

/**
 * @author root
 * 
 */
public class JobUtil {

	private static Logger logger = Logger.getLogger(JobUtil.class);

	private static SchedulerFactory sf;
	private static Scheduler scheduler;

	/**
	 * @category 主函
	 */
	public boolean loadJobs(Snmp snmp) {

		// 初始化 信息存储类

		sf = new StdSchedulerFactory();
		try {
			scheduler = sf.getScheduler();
			// snmp的任务
			JobDetail snmpjob = JobBuilder.newJob(SnmpJob.class)
					.withIdentity("snmpjob", "snmp").build(); // 加载 SNMP 的job

			snmpjob.getJobDataMap().put("snmp", snmp);
			// snmp的定时器
			CronTrigger snmptrigger = TriggerBuilder
					.newTrigger()
					.withIdentity("snmpjobtrigger", "snmp")
					.withSchedule(
							CronScheduleBuilder.cronSchedule(GetConfig
									.getValue("snmptime"))).build();
			scheduler.scheduleJob(snmpjob, snmptrigger);
			return true;
		} catch (SchedulerException e) {
			e.printStackTrace();
			logger.error("初始化定时任务失败", e);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return false;
	}

	public boolean ActiveJobs() {
		try {
			scheduler.start();
			// // TriggerKey tk = new TriggerKey("snmpjobtrigger", "snmp");
			// JobKey jobKey = new JobKey("snmpjob", "snmp");
			// List<? extends Trigger> triggersOfJob = scheduler
			// .getTriggersOfJob(jobKey);
			// Trigger trigger = triggersOfJob.get(0);
			// if ((trigger.getNextFireTime().getTime() - System
			// .currentTimeMillis()) > 90000) {
			// // 小于 一分钟的时间 不立即执行
			// System.out.println("立即执行任务");
			//
			// scheduler.triggerJob(jobKey);
			// }
			return true;
		} catch (SchedulerException e) {
			logger.error("SchedulerException", e);
		}

		return false;
	}
}
